from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QTableWidget, 
                            QTableWidgetItem, QHeaderView)
from PyQt5.QtCore import Qt
from qfluentwidgets import InfoBar, InfoBarPosition, PrimaryPushButton, SubtitleLabel
import os
import numpy as np

class PointsEditorDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('点对编辑器')
        self.resize(600, 500)
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout(self)
        
        # 添加标题
        title = SubtitleLabel('路径点对编辑器', self)
        layout.addWidget(title, alignment=Qt.AlignCenter)
        
        # 创建表格
        self.table = QTableWidget()
        self.table.setColumnCount(4)
        self.table.setHorizontalHeaderLabels(['起点X', '起点Y', '终点X', '终点Y'])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        layout.addWidget(self.table)
        
        # 添加按钮
        btn_layout = QHBoxLayout()
        load_btn = PrimaryPushButton('加载点对', self)
        save_btn = PrimaryPushButton('保存修改', self)
        
        # 设置按钮大小
        for btn in [load_btn, save_btn]:
            btn.setFixedWidth(200)
            btn.setFixedHeight(40)
            
        load_btn.clicked.connect(self.load_points)
        save_btn.clicked.connect(self.save_points)
        btn_layout.addWidget(load_btn)
        btn_layout.addWidget(save_btn)
        layout.addLayout(btn_layout)

    def load_points(self):
        """加载路径点对"""
        try:
            current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            points_file = os.path.join(current_dir, "data", "point_pairs.txt")
            
            if not os.path.exists(points_file):
                InfoBar.warning(
                    title='警告',
                    content='请先生成点对数据',
                    parent=self
                )
                return
            
            # 读取点对数据
            with open(points_file, 'r') as f:
                # 读取第一行获取点对数量
                num_pairs = int(f.readline().strip())
                # 读取后续的点对数据
                lines = f.readlines()
            
            # 设置表格行数
            self.table.setRowCount(num_pairs)
            
            # 填充数据
            for i, line in enumerate(lines):
                if i >= num_pairs:  # 确保不超过第一行指定的点对数
                    break
                points = line.strip().split()
                if len(points) == 4:  # 确保每行有4个数据
                    for j, point in enumerate(points):
                        item = QTableWidgetItem(point)
                        item.setTextAlignment(Qt.AlignCenter)
                        self.table.setItem(i, j, item)
            
            InfoBar.success(
                title='成功',
                content='点对数据加载成功',
                parent=self
            )
        except Exception as e:
            InfoBar.error(
                title='错误',
                content=f'加载点对失败: {str(e)}',
                parent=self
            )

    def save_points(self):
        """保存点对数据"""
        try:
            if self.table.rowCount() == 0:
                InfoBar.warning(
                    title='警告',
                    content='没有要保存的数据',
                    parent=self
                )
                return
            
            # 收集数据
            points_data = []
            valid_pairs = 0
            
            for row in range(self.table.rowCount()):
                row_data = []
                for col in range(4):
                    item = self.table.item(row, col)
                    if item and item.text():
                        row_data.append(item.text())
                if len(row_data) == 4:  # 确保有完整的点对数据
                    points_data.append(' '.join(row_data))
                    valid_pairs += 1
            
            # 保存数据
            current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            points_file = os.path.join(current_dir, "data", "point_pairs.txt")
            
            with open(points_file, 'w') as f:
                # 首先写入有效点对的数量
                f.write(f"{valid_pairs}\n")
                # 然后写入点对数据
                f.write('\n'.join(points_data))
            
            InfoBar.success(
                title='成功',
                content='点对数据保存成功',
                parent=self
            )
        except Exception as e:
            InfoBar.error(
                title='错误',
                content=f'保存点对失败: {str(e)}',
                parent=self
            )
